package cn.stylefeng.guns.modular.gridsystem.tcp.rpcTcp;

import cn.stylefeng.guns.modular.gridsystem.tcp.rpcTcp.handle.NettyClientHandlerDemo;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import org.springframework.context.annotation.Configuration;

/**
 * 通过netty操控rpc声相仪发送指令
 * @author cxy
 * @data 2023/6/26 9:49
 */
//@Configuration
public class TcpClient {
    static {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EventLoopGroup group = null;
                ChannelFuture channelFuture = null;

                //1.创建线程组
                group = new NioEventLoopGroup();
                //2.创建bootstrap
                Bootstrap bootstrap = new Bootstrap();
                Bootstrap handler = bootstrap.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new NettyClientHandlerDemo());
                            }
                        });
                try {
                    //启动客户端
                    channelFuture = bootstrap.connect("192.168.2.16", 8000).sync();
                    //channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("-nt \n"+message+"\n", CharsetUtil.UTF_8));
                    while (true) {
                        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("-nt \n FTP/audioFileSaveStart -n 16 \n", CharsetUtil.UTF_8));

                        try {
                            Thread.sleep(15000);
                            //System.out.println("一分钟到了");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //channelFuture.channel().closeFuture().sync();
                } catch (Exception e) {
                    group.shutdownGracefully();
                }

            }
        }).start();

    }
}
